﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Data;
using System.Data.Common;
using System.Text;
using System.Text.RegularExpressions;

namespace Vit.Common.Extensions
{
    public static class DataContextExtension
    {
        public static IDataReader ExecuteReader<T>(this T context, string sql)
                 where T : DataContext, new()
        {
            DbCommand cmd = CreateCommand(context, sql, CommandType.Text);
            if (cmd != null)
            {
                if (context.Connection.State != ConnectionState.Open)
                    context.Connection.Open();
                return cmd.ExecuteReader(CommandBehavior.CloseConnection);
            }
            return null;
        }

        public static object ExecuteScalar<T>(this T context, string sql)
                    where T : DataContext, new()
        {
            DbCommand cmd = CreateCommand(context, sql, CommandType.Text);
            if (cmd != null)
            {
                if (context.Connection.State != ConnectionState.Open)
                    context.Connection.Open();
                return cmd.ExecuteScalar();
            }
            return null;
        }

        public static int ExecuteNonQuery<T>(this T context, string sql)
                     where T : DataContext, new()
        {
            DbCommand cmd = CreateCommand(context, sql, CommandType.Text);
            if (cmd != null)
            {
                if (context.Connection.State != ConnectionState.Open)
                    context.Connection.Open();
                return cmd.ExecuteNonQuery();
            }
            return -1;
        }

        public static DbCommand CreateCommand<T>(this T context, string sql, CommandType cmdType)
                     where T : DataContext, new()
        {
            if (string.IsNullOrEmpty(sql))
                return null;
            DbCommand cmd = context.Connection.CreateCommand();
            cmd.CommandText = sql;
            cmd.CommandType = cmdType;
            return cmd;
        }

        public static List<T> ExecuteQuery<T>(this DataContext dataContext, IQueryable query)
        {
            return ExecuteQuery<T>(dataContext, query, true);
        }

        public static List<T> ExecuteQuery<T>(this DataContext dataContext, IQueryable query, bool withNoLock)
        {
            var command = dataContext.GetCommand(query, withNoLock);

            if (dataContext.Connection.State != ConnectionState.Open)
                dataContext.Connection.Open();

            using (DbDataReader reader = command.ExecuteReader())
            {
                return dataContext.Translate<T>(reader).ToList();
            }
        }

        private static Regex s_withNoLockRegex = new Regex(@"(] AS \[t\d+\])", RegexOptions.Compiled);

        private static string AddWithNoLock(string cmdText)
        {
            IEnumerable<Match> matches =
                s_withNoLockRegex.Matches(cmdText).Cast<Match>()
                .OrderByDescending(m => m.Index);
            foreach (Match m in matches)
            {
                int splitIndex = m.Index + m.Value.Length;
                cmdText =
                    cmdText.Substring(0, splitIndex) + " WITH (NOLOCK)" +
                    cmdText.Substring(splitIndex);
            }

            return cmdText;
        }

        private static DbCommand GetCommand(this DataContext dataContext, IQueryable query, bool withNoLock)
        {
            DbCommand command = (DbCommand)dataContext.GetCommand(query);

            if (withNoLock)
            {
                command.CommandText = AddWithNoLock(command.CommandText);
            }

            return command;
        }
    }
}
